const chalk = require('chalk');
const yaml = require('js-yaml');
const fs = require('fs-extra');

function queryResourcesPath() {
  const rootPath = __dirname;
  const yamlPath = `${rootPath}/plugin.yaml`;

  if (!fs.pathExistsSync(yamlPath)) {
    console.log(chalk.red('当前目录未找到plugin.yaml文件'));
    process.exit(1);
  }

  const docObj = yaml.load(fs.readFileSync(yamlPath, 'utf8'));
  const resources = docObj.app.resources || [];
  const fields = docObj.app.fields || [];
  const resourcesPath = [];
  const errorPath = [];

  const checkFile = (filePath, name, path, errorFlag) => {
    try {
      fs.statSync(filePath);
      resourcesPath.push({ name, path });
    } catch (e) {
      if (errorFlag) {
        errorPath.push({ name, path });
      }
    }
  };

  resources.filter(item => {
    return item.key !== 'app_for_obj_copy_link';
  }).forEach((item) => {
    const filePath = `${rootPath}/resources/${item.path}`;
    checkFile(filePath, item.name, item.path, true);
  });

  fields.forEach((item) => {
    const filePath = `${rootPath}/resources/${item.validate}.js`;
    checkFile(filePath, item.name, item.validate, false);
  });

  if (errorPath.length) {
    const errorFiles = errorPath.map(error => error.path);
    console.log(chalk.red(`找不到指定文件: ${errorFiles.join('、')}`));
  }

  return resourcesPath;
}

module.exports = { queryResourcesPath };
